package com.ruoyi.config;

import java.util.Properties;
import java.util.Random;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.text.impl.DefaultTextCreator;
import com.google.code.kaptcha.util.Config;
import com.ruoyi.constant.Constants;
import com.ruoyi.core.RepeatSubmitInterceptor;
import lombok.AllArgsConstructor;
import org.mybatis.spring.annotation.MapperScan;
import org.quartz.simpl.SimpleThreadPool;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.http.CacheControl;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.sql.DataSource;

import static com.google.code.kaptcha.Constants.*;

/**
 * 程序注解配置
 *
 * 
 */
@Configuration
// 表示通过aop框架暴露该代理对象,AopContext能够访问
@EnableAspectJAutoProxy(exposeProxy = true)
// 指定要扫描的Mapper类的包的路径
@MapperScan("com.ruoyi.**.mapper")
public class AppConfig {
    /**
     * 时区配置
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jacksonObjectMapperCustomization() {
        return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder.timeZone(TimeZone.getDefault());
    }

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置访问源地址
        config.addAllowedOriginPattern("*");
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 有效期 1800秒
        config.setMaxAge(1800L);
        // 添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(DataSource dataSource) {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setDataSource(dataSource);

        // quartz参数
        Properties prop = new Properties();
        prop.put("org.quartz.scheduler.instanceName", "RuoyiScheduler");
        prop.put("org.quartz.scheduler.instanceId", "AUTO");
        // 线程池配置
        prop.put("org.quartz.threadPool.class", SimpleThreadPool.class.getName());
        prop.put("org.quartz.threadPool.threadCount", "20");
        prop.put("org.quartz.threadPool.threadPriority", "5");
        // JobStore配置
        prop.put("org.quartz.jobStore.class", org.springframework.scheduling.quartz.LocalDataSourceJobStore.class.getName());
        // 集群配置
        prop.put("org.quartz.jobStore.isClustered", "true");
        prop.put("org.quartz.jobStore.clusterCheckinInterval", "15000");
        prop.put("org.quartz.jobStore.maxMisfiresToHandleAtATime", "10");
        prop.put("org.quartz.jobStore.txIsolationLevelSerializable", "true");

        // sqlserver 启用
        // prop.put("org.quartz.jobStore.selectWithLockSQL", "SELECT * FROM {0}LOCKS UPDLOCK WHERE LOCK_NAME = ?");
        prop.put("org.quartz.jobStore.misfireThreshold", "12000");
        prop.put("org.quartz.jobStore.tablePrefix", "QRTZ_");
        factory.setQuartzProperties(prop);

        factory.setSchedulerName("RuoyiScheduler");
        // 延时启动
        factory.setStartupDelay(1);
        factory.setApplicationContextSchedulerContextKey("applicationContextKey");
        // 可选，QuartzScheduler
        // 启动时更新己存在的Job，这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了
        factory.setOverwriteExistingJobs(true);
        // 设置自动启动，默认为true
        factory.setAutoStartup(true);

        return factory;
    }

    // 验证码配置
    @Configuration
    public static class CaptchaConfig {
        @Bean(name = "captchaProducer")
        public DefaultKaptcha getKaptchaBean() {
            DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
            Properties properties = new Properties();
            // 是否有边框 默认为true 我们可以自己设置yes，no
            properties.setProperty(KAPTCHA_BORDER, "yes");
            // 验证码文本字符颜色 默认为Color.BLACK
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "black");
            // 验证码图片宽度 默认为200
            properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
            // 验证码图片高度 默认为50
            properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60");
            // 验证码文本字符大小 默认为40
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "38");
            // KAPTCHA_SESSION_KEY
            properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCode");
            // 验证码文本字符长度 默认为5
            properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
            // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
            // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
            properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy");
            Config config = new Config(properties);
            defaultKaptcha.setConfig(config);
            return defaultKaptcha;
        }

        @Bean(name = "captchaProducerMath")
        public DefaultKaptcha getKaptchaBeanMath() {
            DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
            Properties properties = new Properties();
            // 是否有边框 默认为true 我们可以自己设置yes，no
            properties.setProperty(KAPTCHA_BORDER, "yes");
            // 边框颜色 默认为Color.BLACK
            properties.setProperty(KAPTCHA_BORDER_COLOR, "105,179,90");
            // 验证码文本字符颜色 默认为Color.BLACK
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue");
            // 验证码图片宽度 默认为200
            properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
            // 验证码图片高度 默认为50
            properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60");
            // 验证码文本字符大小 默认为40
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "35");
            // KAPTCHA_SESSION_KEY
            properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCodeMath");
            // 验证码文本生成器
            properties.setProperty(KAPTCHA_TEXTPRODUCER_IMPL, KaptchaTextCreator.class.getName());
            // 验证码文本字符间距 默认为2
            properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "3");
            // 验证码文本字符长度 默认为5
            properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "6");
            // 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
            properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
            // 验证码噪点颜色 默认为Color.BLACK
            properties.setProperty(KAPTCHA_NOISE_COLOR, "white");
            // 干扰实现类

            properties.setProperty(KAPTCHA_NOISE_IMPL, com.google.code.kaptcha.impl.NoNoise.class.getName());
            // 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
            properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, com.google.code.kaptcha.impl.ShadowGimpy.class.getName());
            Config config = new Config(properties);
            defaultKaptcha.setConfig(config);
            return defaultKaptcha;
        }
    }

    public static class KaptchaTextCreator extends DefaultTextCreator {
        private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(",");

        @Override
        public String getText() {
            int result = 0;
            Random random = new Random();
            int x = random.nextInt(10);
            int y = random.nextInt(10);
            StringBuilder suChinese = new StringBuilder();
            int randomInt = random.nextInt(3);
            if (randomInt == 0) {
                result = x * y;
                suChinese.append(CNUMBERS[x]);
                suChinese.append("*");
                suChinese.append(CNUMBERS[y]);
            } else if (randomInt == 1) {
                if ((x != 0) && y % x == 0) {
                    result = y / x;
                    suChinese.append(CNUMBERS[y]);
                    suChinese.append("/");
                    suChinese.append(CNUMBERS[x]);
                } else {
                    result = x + y;
                    suChinese.append(CNUMBERS[x]);
                    suChinese.append("+");
                    suChinese.append(CNUMBERS[y]);
                }
            } else {
                if (x >= y) {
                    result = x - y;
                    suChinese.append(CNUMBERS[x]);
                    suChinese.append("-");
                    suChinese.append(CNUMBERS[y]);
                } else {
                    result = y - x;
                    suChinese.append(CNUMBERS[y]);
                    suChinese.append("-");
                    suChinese.append(CNUMBERS[x]);
                }
            }
            suChinese.append("=?@").append(result);
            return suChinese.toString();
        }
    }

    @Configuration
    public static class I18nConfig {
        @Bean
        public LocaleResolver localeResolver() {
            SessionLocaleResolver slr = new SessionLocaleResolver();
            // 默认语言
            slr.setDefaultLocale(Constants.DEFAULT_LOCALE);
            return slr;
        }

        @Bean
        public LocaleChangeInterceptor localeChangeInterceptor() {
            LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
            // 参数名
            lci.setParamName("lang");
            return lci;
        }
    }

    @AllArgsConstructor
    @Configuration(proxyBeanMethods = false)
    public static class WebMvcConfig implements WebMvcConfigurer {
        final RepeatSubmitInterceptor repeatSubmitInterceptor;
        final RuoYiConfig config;
        final LocaleChangeInterceptor localeChangeInterceptor;

        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            /** 本地文件上传路径 */
            registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**")
                    .addResourceLocations("file:" + config.getProfile() + "/");

            /** swagger配置 */
            registry.addResourceHandler("/swagger-ui/**")
                    .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
                    .setCacheControl(CacheControl.maxAge(5, TimeUnit.HOURS).cachePublic());
        }

        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
            registry.addInterceptor(localeChangeInterceptor);
        }


    }
}
